/*
 *
 * Author Administrator
 * Date 2021/9/9 10:41
 */
package cn.safekeeper.guide.admin.filter;

import cn.safekeeper.common.exception.SafeKeeperPermissionException;
import cn.safekeeper.core.SafeKeeper;
import cn.safekeeper.guide.admin.constant.Msg;
import cn.safekeeper.guide.admin.constant.MsgObj;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Component
public class MyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String uri = ((HttpServletRequest) request).getRequestURI();
        System.out.println("请求路径=" + uri);
        if(isExclude(uri)){
            chain.doFilter(request, response);
            return;
        }
        String permission = uri.replace("/", ":").substring(1);
        try {
            SafeKeeper.safeDefault().checkPermission(permission);
        } catch (SafeKeeperPermissionException e) {
            if(e.getCode() == 1000){
                MsgObj msgObj = MsgObj.error(Msg.NO_PERMISSION_MSG);
                responseWeb((HttpServletResponse) response, msgObj);
                return;
            }
        }
        chain.doFilter(request, response);
    }

    //排除的uri
    private boolean isExclude(String uri){
        List<String> excludeList = new ArrayList<>();
        excludeList.add("login");
        excludeList.add("captchaImage");
        excludeList.add("getInfo");
        excludeList.add("logout");
        excludeList.add("getRouters");
        excludeList.add("roleMenuTreeselect");
        excludeList.add("treeselect");
        excludeList.add("optionselect");
        excludeList.add("configKey");
        excludeList.add("dict");
        for(String excludeStr : excludeList){
            if(uri.contains(excludeStr)){
                return true;
            }
        }
        return false;
    }

    //返回页面
    private void responseWeb(HttpServletResponse response, Object object) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        out.append(object.toString());
    }
}
